package pannel.recipe;

import system.BasePage;
import pannel.user.User;
import pannel.category.Category;
import pannel.category.CategoryDao;
import layout.WrapLayout;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.time.format.DateTimeFormatter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class RecipeListPage extends BasePage {
    private DefaultTableModel model;
    private List<Recipe> recipeList = new ArrayList<>();
    private JTable table;
    private JTextField searchField;
    private JComboBox<Category> categoryComboBox;
    private int currentPage = 1;
    private int pageSize = 10;
    private JLabel pageInfoLabel;
    private RecipeDao recipeDao;
    private CategoryDao categoryDao;
    private int totalRecords = 0;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private JPanel cardsPanel;
    private static final int CARDS_PER_ROW = 3;
    private static final double CARD_RATIO = 0.45;
    private static final double IMAGE_RATIO = 0.6;
    private static final int CARD_GAP = 15;
    private static final int IMAGE_SIZE = 200;

    public RecipeListPage(User user) {
        super(user);
        this.recipeDao = new RecipeDao();
        this.categoryDao = new CategoryDao();
        initPageContent();
    }

    @Override
    protected void initPageContent() {
        setPageTitle("菜谱列表");
        if ("ADMIN".equals(getCurrentUser().getRole())) {
            setupAdminContent();
            refreshTable();
        } else {
            setupUserContent();
            SwingUtilities.invokeLater(() -> {
                try {
                    refreshCards();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "加载数据失败：" + e.getMessage());
                }
            });
        }
    }

    private void setupUserContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        categoryComboBox = new JComboBox<>();
        
        try {
            loadCategories();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载分类数据失败：" + e.getMessage());
        }

        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("菜谱名称："));
        searchPanel.add(searchField);
        searchPanel.add(new JLabel("分类："));
        searchPanel.add(categoryComboBox);
        searchPanel.add(searchButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);

        // 修改卡片面板布局为垂直方向
        cardsPanel = new JPanel();
        cardsPanel.setLayout(new BoxLayout(cardsPanel, BoxLayout.Y_AXIS));
        cardsPanel.setBackground(Color.WHITE);
        
        // 为每个卡片添加垂直间距
        cardsPanel.setBorder(BorderFactory.createEmptyBorder(CARD_GAP, CARD_GAP, CARD_GAP, CARD_GAP));

        // 创建滚动面板
        JScrollPane scrollPane = new JScrollPane(cardsPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshContent();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshContent();
            }
        });

        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshContent();
        });

        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    private void setupAdminContent() {
        contentArea.setLayout(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(20);
        categoryComboBox = new JComboBox<>();
        
        try {
            loadCategories();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载分类数据失败：" + e.getMessage());
        }

        JButton searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("菜谱名称："));
        searchPanel.add(searchField);
        searchPanel.add(new JLabel("分类："));
        searchPanel.add(categoryComboBox);
        searchPanel.add(searchButton);

        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolBar.setBackground(Color.WHITE);

        JButton addButton = new JButton("新增菜谱");
        JButton deleteButton = new JButton("删除菜谱");
        JButton editButton = new JButton("编辑菜谱");

        toolBar.add(addButton);
        toolBar.add(deleteButton);
        toolBar.add(editButton);

        topPanel.add(searchPanel, BorderLayout.NORTH);
        topPanel.add(toolBar, BorderLayout.CENTER);

        // 表格设置
        String[] columnNames = {"ID", "菜谱名称", "分类", "描述", "创建时间", "图片"};
        model = new DefaultTableModel(new Object[0][], columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 5) return ImageIcon.class;
                return super.getColumnClass(columnIndex);
            }
        };
        
        table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.setRowHeight(60); // 设置行高以适应图片
        
        // 设置图片列的渲染器
        table.getColumnModel().getColumn(5).setCellRenderer(new ImageRenderer());

        // 分页面板
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");
        pageInfoLabel = new JLabel();

        paginationPanel.add(prevButton);
        paginationPanel.add(pageInfoLabel);
        paginationPanel.add(nextButton);

        // 按钮事件处理
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                refreshContent();
            }
        });

        nextButton.addActionListener(e -> {
            int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
            if (currentPage < totalPages) {
                currentPage++;
                refreshContent();
            }
        });

        searchButton.addActionListener(e -> {
            currentPage = 1;
            refreshContent();
        });

        // 添加菜谱按钮事件
        addButton.addActionListener(e -> {
            RecipeDialog dialog = new RecipeDialog(null, "新增菜谱", null);
            if (dialog.showDialog()) {
                try {
                    Recipe newRecipe = Recipe.builder()
                            .name(dialog.getRecipeName())
                            .description(dialog.getDescription())
                            .categoryId(dialog.getSelectedCategory().getId())
                            .imagePath(dialog.getImagePath())
                            .build();

                    if (recipeDao.insert(newRecipe)) {
                        JOptionPane.showMessageDialog(this, "添加成功！");
                        refreshContent();
                    } else {
                        JOptionPane.showMessageDialog(this, "添加失败！");
                    }
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(this, "添加失败：" + ex.getMessage());
                }
            }
        });

        // 删除菜谱按钮事件
        deleteButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                int id = (int) table.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(
                        this,
                        "确定要删除这个菜谱吗？",
                        "删除确认",
                        JOptionPane.YES_NO_OPTION);

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        if (recipeDao.deleteById(id)) {
                            JOptionPane.showMessageDialog(this, "删除成功！");
                            refreshContent();
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "删除失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的菜谱");
            }
        });

        // 编辑菜谱按钮事件
        editButton.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                Recipe selectedRecipe = recipeList.get(selectedRow);
                RecipeDialog dialog = new RecipeDialog(null, "编辑菜谱", selectedRecipe);
                if (dialog.showDialog()) {
                    try {
                        selectedRecipe.setName(dialog.getRecipeName());
                        selectedRecipe.setDescription(dialog.getDescription());
                        selectedRecipe.setCategoryId(dialog.getSelectedCategory().getId());
                        selectedRecipe.setImagePath(dialog.getImagePath());

                        if (recipeDao.updateById(selectedRecipe)) {
                            JOptionPane.showMessageDialog(this, "更新成功！");
                            refreshContent();
                        } else {
                            JOptionPane.showMessageDialog(this, "更新失败！");
                        }
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "更新失败：" + ex.getMessage());
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要编辑的菜谱");
            }
        });

        JScrollPane scrollPane = new JScrollPane(table);
        contentArea.add(topPanel, BorderLayout.NORTH);
        contentArea.add(scrollPane, BorderLayout.CENTER);
        contentArea.add(paginationPanel, BorderLayout.SOUTH);
    }

    private void loadCategories() {
        try {
            if (categoryDao == null) {
                categoryDao = new CategoryDao();
            }
            List<Category> categories = categoryDao.findAll();
            if (categories == null) {
                categories = new ArrayList<>();
            }
            
            DefaultComboBoxModel<Category> model = new DefaultComboBoxModel<>();
            model.addElement(null); // 添加空选项
            for (Category category : categories) {
                model.addElement(category);
            }
            categoryComboBox.setModel(model);
            
            // 设置渲染器来显示分类名称
            categoryComboBox.setRenderer(new DefaultListCellRenderer() {
                @Override
                public Component getListCellRendererComponent(JList<?> list, Object value, 
                        int index, boolean isSelected, boolean cellHasFocus) {
                    if (value == null) {
                        value = "全部分类";
                    } else {
                        value = ((Category) value).getName();
                    }
                    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                }
            });
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "加载分类数据失败：" + e.getMessage());
        }
    }

    private void refreshTable() {
        SwingUtilities.invokeLater(() -> {
            try {
                String searchText = searchField.getText().trim();
                Category selectedCategory = (Category) categoryComboBox.getSelectedItem();
                Integer categoryId = selectedCategory != null ? selectedCategory.getId() : null;
                
                recipeList = recipeDao.pageQuery(searchText, categoryId, currentPage, pageSize);
                totalRecords = recipeDao.getTotalCount(searchText, categoryId);

                model.setRowCount(0);
                for (Recipe recipe : recipeList) {
                    model.addRow(new Object[]{
                            recipe.getId(),
                            recipe.getName(),
                            recipe.getCategoryName(),
                            recipe.getDescription(),
                            recipe.getCreateTime().format(DATE_FORMATTER),
                            createScaledImageIcon(recipe.getImagePath())
                    });
                }
                updatePageInfo();
                table.repaint();
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, "获取菜谱数据失败：" + e.getMessage());
            }
        });
    }

    private ImageIcon createScaledImageIcon(String path, int width, int height) {
        try {
            ImageIcon originalIcon;
            if (path == null || path.isEmpty()) {
                return createDefaultIcon(width, height);
            }
            
            // 尝试从文件加载图片
            originalIcon = new ImageIcon(path);
            if (originalIcon.getIconWidth() <= 0) {
                return createDefaultIcon(width, height);
            }

            // 缩放图片
            Image scaledImage = originalIcon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
            
            // 清理原始图片资源
            originalIcon.getImage().flush();
            originalIcon = null;
            
            ImageIcon scaledIcon = new ImageIcon(scaledImage);
            return scaledIcon;
        } catch (Exception e) {
            return createDefaultIcon(width, height);
        }
    }

    private ImageIcon createDefaultIcon(int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        g2d.setColor(Color.LIGHT_GRAY);
        g2d.fillRect(0, 0, width, height);
        g2d.dispose();
        return new ImageIcon(image);
    }

    private ImageIcon createScaledImageIcon(String path) {
        return createScaledImageIcon(path, 50, 50);
    }

    private ImageIcon createDefaultIcon() {
        return createDefaultIcon(50, 50);
    }

    private void updatePageInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }

    private static class ImageRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                     boolean isSelected, boolean hasFocus,
                                                     int row, int column) {
            if (value instanceof ImageIcon) {
                JLabel label = new JLabel((ImageIcon) value);
                label.setHorizontalAlignment(JLabel.CENTER);
                if (isSelected) {
                    label.setBackground(table.getSelectionBackground());
                    label.setOpaque(true);
                }
                return label;
            }
            return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        }
    }

    private void refreshContent() {
        try {
            if ("ADMIN".equals(getCurrentUser().getRole())) {
                refreshTable();
            } else {
                refreshCards();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载数据��败：" + e.getMessage());
        }
    }

    private void refreshCards() {
        try {
            String searchText = searchField.getText().trim();
            Category selectedCategory = (Category) categoryComboBox.getSelectedItem();
            Integer categoryId = selectedCategory != null ? selectedCategory.getId() : null;
            
            recipeList = recipeDao.pageQuery(searchText, categoryId, currentPage, pageSize);
            totalRecords = recipeDao.getTotalCount(searchText, categoryId);

            cardsPanel.removeAll();
            
            for (Recipe recipe : recipeList) {
                cardsPanel.add(createRecipeCard(recipe));
            }

            updatePaginationInfo();
            cardsPanel.revalidate();
            cardsPanel.repaint();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "获取菜谱数据失败：" + e.getMessage());
        }
    }

    private JPanel createRecipeCard(Recipe recipe) {
        JPanel card = new JPanel();
        card.setLayout(new BorderLayout(0, 10));
        
        // 调整卡片大小以适应容器宽度
        card.setPreferredSize(new Dimension(800, 300)); // 减小高度，增加宽度
        
        // 添加卡片间距
        card.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.LIGHT_GRAY),
            BorderFactory.createEmptyBorder(10, 10, 10, 10)
        ));
        card.setBackground(Color.WHITE);
        
        // 使用水平布局包装面板
        JPanel wrapperPanel = new JPanel();
        wrapperPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        wrapperPanel.setBackground(Color.WHITE);
        wrapperPanel.add(card);

        // 图片和内容使用水平布局
        JPanel contentPanel = new JPanel(new BorderLayout(20, 0));
        contentPanel.setBackground(Color.WHITE);

        // 图片
        JLabel imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(JLabel.CENTER);
        imageLabel.setPreferredSize(new Dimension(250, 250));
        ImageIcon imageIcon = new ImageIcon(recipe.getImagePath());
        Image image = imageIcon.getImage().getScaledInstance(200, 200, Image.SCALE_SMOOTH);
        imageLabel.setIcon(new ImageIcon(image));

        // 信息面板
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
        infoPanel.setBackground(Color.WHITE);

        // 标题
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setBackground(Color.WHITE);
        
        JLabel nameLabel = new JLabel(recipe.getName());
        nameLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        
        JLabel categoryLabel = new JLabel("分类: " + recipe.getCategoryName());
        categoryLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        
        titlePanel.add(nameLabel, BorderLayout.NORTH);
        titlePanel.add(categoryLabel, BorderLayout.CENTER);

        // 描述
        JTextArea descArea = new JTextArea(recipe.getDescription());
        descArea.setWrapStyleWord(true);
        descArea.setLineWrap(true);
        descArea.setEditable(false);
        descArea.setBackground(Color.WHITE);
        descArea.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        descArea.setPreferredSize(new Dimension(260, 80));

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(Color.WHITE);

        JButton commentButton = new JButton("查看评论");
        commentButton.addActionListener(e -> {
            CommentDialog dialog = new CommentDialog(
                SwingUtilities.getWindowAncestor(this),
                recipe,
                getCurrentUser()
            );
            dialog.setVisible(true);
        });

        JButton favoriteButton = new JButton();
        try {
            boolean isFavorite = recipeDao.isFavorite(getCurrentUser().getId(), recipe.getId());
            updateFavoriteButton(favoriteButton, isFavorite);
        } catch (SQLException e) {
            favoriteButton.setText("收藏");
        }

        favoriteButton.addActionListener(e -> {
            try {
                boolean currentlyFavorite = recipeDao.isFavorite(getCurrentUser().getId(), recipe.getId());
                boolean success;
                if (currentlyFavorite) {
                    success = recipeDao.removeFavorite(getCurrentUser().getId(), recipe.getId());
                    if (success) {
                        JOptionPane.showMessageDialog(this, "取消收藏成功！");
                        updateFavoriteButton(favoriteButton, false);
                    } else {
                        JOptionPane.showMessageDialog(this, "取消收藏失败！");
                    }
                } else {
                    success = recipeDao.addFavorite(getCurrentUser().getId(), recipe.getId());
                    if (success) {
                        JOptionPane.showMessageDialog(this, "收藏成功！");
                        updateFavoriteButton(favoriteButton, true);
                    } else {
                        JOptionPane.showMessageDialog(this, "收藏失败！");
                    }
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage());
            }
        });

        buttonPanel.add(commentButton);
        buttonPanel.add(favoriteButton);

        infoPanel.add(titlePanel);
        infoPanel.add(Box.createVerticalStrut(10));
        infoPanel.add(descArea);
        infoPanel.add(buttonPanel);

        contentPanel.add(imageLabel, BorderLayout.WEST);
        contentPanel.add(infoPanel, BorderLayout.CENTER);
        
        card.add(contentPanel, BorderLayout.CENTER);

        return wrapperPanel;
    }

    private void updateFavoriteButton(JButton button, boolean isFavorite) {
        if (isFavorite) {
            button.setText("取消收藏");
            button.setForeground(new Color(220, 20, 60));
        } else {
            button.setText("收藏");
            button.setForeground(new Color(30, 144, 255));
        }
    }

    private void updatePaginationInfo() {
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);
        pageInfoLabel.setText(String.format("第 %d/%d 页  共%d条记录", currentPage, totalPages, totalRecords));
    }
} 